package com.hua.argi;

/**
 * @author: _hua
 * @created: 2019/3/31.
 * @updater:
 * @description:
 */
public class SortLink {

    private LinkNode head;

    public SortLink(){
        this.head = null;
    }
    public boolean isEmpty(){
        return  head==null;
    }

    public void insert(LinkNode node){
        int key = node.getKey();

        LinkNode current = head;
        LinkNode preNode = null;

        while (current!=null&&key>current.getKey()){
            preNode = current;
            current =current.next;
        }

        if(preNode==null){
            node.next=head;
            head=node;
        }else{
            preNode.next=node;
            node.next=current;
        }
    }

    public void delete(int key){
        LinkNode previous = null;
        LinkNode current = head;

        if(isEmpty()){
            System.out.println("Linked is Empty!!!");
            return;
        }

        while (current!=null&&key!=current.getKey()){
            previous =current;
            current=current.next;
        }

        if(previous==null){
            head=head.next;
        }else {
            previous.next=current.next;
        }
    }

    public LinkNode find(int key){
        LinkNode current = head;
        while(current != null && current.getKey() <= key){
            if(current.getKey() == key){
                return current;
            }
            current = current.next;
        }
        return null;
    }

    public void displayLink(){
        System.out.println("Link(First->Last)");
        LinkNode current = head;
        while(current != null){
            current.displayLink();
            current = current.next;
        }
        System.out.println("");
    }


    class LinkNode{
        private int iData;
        public LinkNode next;
        public LinkNode(int iData){
            this.iData = iData;
        }
        public int getKey(){
            return iData;
        }
        public void displayLink(){
            System.out.println(iData + " ");
        }
    }
}
